﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Text;
using OfficeOpenXml;

using Analysis.DAL;
using Analysis.DAL.Repositories;
using Analysis.Entities;
using Analysis.Code;
using System.Web.Security;

namespace Analysis
{
    public partial class TargetSCU : BaseGridPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!AccessConfirm("MML"))
            {
                throw new HttpException(401, "Доступ закрыт");
            }
            if (!IsPostBack)
            {
                LoadData();
            }

            if (IsAdmin)
            {
                btnCustomColumn.Visible = true;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            PageName = "TargetSCU";
            FileName = "Целевой ассортимент";

            if (!IsPostBack)
            {
                LoadCombo();
                LoadDataFromDb();
            }

            InitGrid();
        }

        public override void LoadDataFromDb()
        {
            // Данные из БД
            GridData = TargetSCURepository.FindTargetSCU(Convert.ToInt32(ddlMonthIdFilter.SelectedValue), Convert.ToInt32(ddlYearIdFilter.SelectedValue));

            // Формируем список кастомных колонок
            GenerateCustomColumnList();
        }

        public override void LoadData()
        {
            DataView dv = GridDataView;
            if (dv.Count == 0)
            {
                IsEmptyGrid = true;
                dv.AddNew();
                dv[0]["IsSelected"] = false;
            }
            grid.DataSource = dv;
            grid.DataBind();
            upMain.Update();

            // Привязываем грид редактора колонок
            ctrlCustomColumnDialog.LoadData(ColumnsList);
        }

        private void LoadCombo()
        {
            ddlYearIdFilter.DataSource = TargetSCURepository.YearCustomCombo();
            ddlYearIdFilter.DataBind();
            ddlYearIdFilter.SelectedValue = DateTime.Today.Year.ToString();

            ddlMonthIdFilter.DataSource = TargetSCURepository.MonthCustomCombo(Convert.ToInt32(ddlYearIdFilter.SelectedValue));
            ddlMonthIdFilter.DataBind();
            ddlMonthIdFilter.SelectedValue = DateTime.Today.Month.ToString();
        }

        public override GridView GetGrid()
        {
            return grid;
        }

        protected override UpdatePanel GetUP()
        {
            return upMain;
        }

        protected override void InitGrid()
        {
            /*TemplateField tf = null;
            Depart depart = null;

            // Настройка колонок юрезов на должности: прячем незадействованные должности
            for (int i = 1; i <= 5; ++i)
            {
                string nameColumn = "Depart" + i.ToString();
                tf = GetColumnByHeader(nameColumn);
                if (tf == null)
                    continue;

                using (var repo = RepositoryFactory.ResolveRepository<SetupRepository>())
                {
                    depart = repo.FindDepartByColumnName(nameColumn);
                }

                if (depart == null)
                    tf.Visible = false;
                else
                    tf.HeaderText = depart.DepartName;
            }*/

            base.InitGrid();
        }

        protected override void grid_RowCreated(Object sender, GridViewRowEventArgs e)
        {
            base.grid_RowCreated(sender, e);
        }

        protected override void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            base.grid_RowDataBound(sender, e);

            DataRowView drv = (DataRowView)e.Row.DataItem;

            if (e.Row.RowType == DataControlRowType.Header)
            {
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (IsEmptyGrid)
                    e.Row.Attributes.Add("style", "display:none;");

                TextBox txt = (TextBox)e.Row.FindControl("txtGroupingName");
                CheckBox chk = (CheckBox)e.Row.FindControl("chbIsSelected");
                if (chk != null)
                {
                    chk.Checked = Convert.ToBoolean(drv["IsSelected"]);
                    if (txt != null)
                        txt.Enabled = chk.Checked;
                }

            } 
        }

        protected void ddlYearIdFilter_SelectedIndexChanged(Object sender, EventArgs e)
        {
            ddlMonthIdFilter.DataSource = TargetSCURepository.MonthCustomCombo(Convert.ToInt32(ddlYearIdFilter.SelectedValue));
            ddlMonthIdFilter.DataBind();

            LoadDataFromDb();
            LoadData();
        }

        protected void ddlMonthIdFilter_SelectedIndexChanged(Object sender, EventArgs e)
        {
            LoadDataFromDb();
            LoadData();
        }

        protected void selected_CheckedChangeOver(object sender, EventArgs e)
        {
            selected_CheckedChange(sender, e);
            LoadData();
        }

        protected void btnSaveTargetSCU_Click(object sender, EventArgs e)
        {
            string result = SaveTargetSCU();
            if (!string.IsNullOrEmpty(result))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", string.Format("alert('{0}');", result), true);
                return;
            }
            else
            {
                LoadDataFromDb();
                LoadData();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('Сохранение успешно завершено!');", true);
            }
        }
        
        protected string SaveTargetSCU()
        {
            string result = "";
            
            foreach (GridViewRow item in grid.Rows)
            {
                if (item.RowType != DataControlRowType.DataRow)
                    continue;
                                
                CheckBox chk = (CheckBox)item.FindControl("chbIsSelected");
                HiddenField hfTargetSCUId = (HiddenField)item.FindControl("hidTargetSCUId");
                // Запись выбрана
                if (chk.Checked)
                {
                    List<KeyValuePair<string, object>> data = new List<KeyValuePair<string, object>>();
                    int id;

                    data.Add(new KeyValuePair<string, object>("LastUpdateUserName", User.Identity.Name));
                    data.Add(new KeyValuePair<string, object>("LastUpdateDateTime", DateTime.Now));

                    if (grid.Columns[6].Visible)
                        data.Add(new KeyValuePair<string, object>("GroupingName", ((TextBox)item.FindControl("txtGroupingName")).Text));

                    // новая запись
                    if (string.IsNullOrEmpty(hfTargetSCUId.Value))
                    {
                        id = -1;
                        
                        data.Add(new KeyValuePair<string, object>("YearId", Convert.ToInt32(ddlYearIdFilter.SelectedValue)));
                        data.Add(new KeyValuePair<string, object>("MonthId", Convert.ToInt32(ddlMonthIdFilter.SelectedValue)));
                        data.Add(new KeyValuePair<string, object>("SCUId", ((HiddenField)item.FindControl("hidSCUId")).Value));
                        data.Add(new KeyValuePair<string, object>("SaleChannelId", ((HiddenField)item.FindControl("hidSaleChannelId")).Value));
                        data.Add(new KeyValuePair<string, object>("StorePointId", ((HiddenField)item.FindControl("hidStorePointId")).Value));
                    }
                    // обновление
                    else
                    {
                        id = Convert.ToInt32(hfTargetSCUId.Value);
                    }
                    TargetSCURepository.EditTargetSCU(id, data);
                }
                else
                {
                    // Запись была выбрана, а теперь - нет (нужно удалить)
                    if (!string.IsNullOrEmpty(hfTargetSCUId.Value))
                        TargetSCURepository.DeleteTargetSCU(Convert.ToInt32(hfTargetSCUId.Value));
                }

            }

            return result;
        }
        
        protected void grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            
        }
       
    }
}